package com.jblog.core.service.blog.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jblog.core.CoreUtil;
import com.jblog.core.dao.blog.PostTagLinkDao;
import com.jblog.core.dao.blog.TagDao;
import com.jblog.core.model.blog.Post;
import com.jblog.core.model.blog.Tag;
import com.jblog.core.model.blog.param.TagParam;
import com.jblog.core.service.blog.TagService;

@Service
public class TagServiceImpl implements TagService {
    
    @Autowired private TagDao tagDao;
    @Autowired private PostTagLinkDao postTagLinkDao;

    @Override
    public Tag findById(Long id) {
        return findOne(new TagParam(id));
    }
    
    public List<Tag> findByPostId(Long id) {
        return findByParam(new TagParam(new Post(id)));
    }

    @Override
    public Tag findByAlisa(String s) {
        return findOne(new TagParam(s));
    }

    @Override
    public List<Tag> findByParam(TagParam p) {
        return tagDao.byParam(p);
    }
    
    @Override
    public Long count(TagParam p) {
        return tagDao.count(p);
    }

    private Tag findOne(TagParam p) {
        List<Tag> es = findByParam(p);
        if (null != es && es.size() == 1) {
            return es.get(0);
        } 
        return null;
    }

    @Override
    public void enDisable(Tag e, boolean able) {
        if (!CoreUtil.checkStatus(e.getStatus(), able)) {
            update(new Tag(e.getId(), CoreUtil.toStatus(able)));
        }
    }

    @Override
    public void save(Tag e) {
        tagDao.save(e);
    }

    @Override
    public void update(Tag e) {
        tagDao.update(e);
    }

    @Override
    public void delete(Long id) {
        postTagLinkDao.deleteByTagPk(id);
        tagDao.deleteByPk(id);
    }
 
}